<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=2">
<meta name="theme-color" content="#222">
<meta name="generator" content="Hexo 4.2.0">
  <link rel="apple-touch-icon" sizes="180x180" href="/myblogs/images/apple-touch-icon-next.png">
  <link rel="icon" type="image/png" sizes="32x32" href="/myblogs/images/favicon-32x32-next.png">
  <link rel="icon" type="image/png" sizes="16x16" href="/myblogs/images/favicon-16x16-next.png">
  <link rel="mask-icon" href="/myblogs/images/logo.svg" color="#222">

<link rel="stylesheet" href="/myblogs/css/main.css">


<link rel="stylesheet" href="/myblogs/lib/font-awesome/css/font-awesome.min.css">
  <link rel="stylesheet" href="/myblogs/lib/pace/pace-theme-minimal.min.css">
  <script src="/myblogs/lib/pace/pace.min.js"></script>


<script id="hexo-configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    hostname: new URL('http://hackmgod.gitee.io').hostname,
    root: '/myblogs/',
    scheme: 'Gemini',
    version: '7.7.0',
    exturl: false,
    sidebar: {"position":"left","display":"post","padding":18,"offset":12,"onmobile":false},
    copycode: {"enable":false,"show_result":false,"style":null},
    back2top: {"enable":true,"sidebar":false,"scrollpercent":false},
    bookmark: {"enable":false,"color":"#222","save":"auto"},
    fancybox: false,
    mediumzoom: false,
    lazyload: false,
    pangu: false,
    comments: {"style":"tabs","active":null,"storage":true,"lazyload":false,"nav":null},
    algolia: {
      appID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    },
    localsearch: {"enable":true,"trigger":"auto","top_n_per_article":1,"unescape":false,"preload":false},
    path: 'search.xml',
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}}
  };
</script>

  <meta name="description" content="模板方法模式（模板方法设计模式）详解">
<meta property="og:type" content="article">
<meta property="og:title" content="【26】模板方法模式（模板方法设计模式）详解">
<meta property="og:url" content="http://hackmgod.gitee.io/2020/01/17/%E3%80%9026%E3%80%91%E6%A8%A1%E6%9D%BF%E6%96%B9%E6%B3%95%E6%A8%A1%E5%BC%8F%EF%BC%88%E6%A8%A1%E6%9D%BF%E6%96%B9%E6%B3%95%E8%AE%BE%E8%AE%A1%E6%A8%A1%E5%BC%8F%EF%BC%89%E8%AF%A6%E8%A7%A3/index.html">
<meta property="og:site_name" content="H.m博客">
<meta property="og:description" content="模板方法模式（模板方法设计模式）详解">
<meta property="og:locale" content="zh_CN">
<meta property="og:image" content="http://c.biancheng.net/uploads/allimg/181116/3-1Q116095405308.gif">
<meta property="og:image" content="http://c.biancheng.net/uploads/allimg/181116/3-1Q11609544UV.gif">
<meta property="og:image" content="http://c.biancheng.net/uploads/allimg/181116/3-1Q116095550123.gif">
<meta property="article:published_time" content="2020-01-17T05:59:17.000Z">
<meta property="article:modified_time" content="2020-01-17T10:10:03.832Z">
<meta property="article:author" content="H.m">
<meta name="twitter:card" content="summary">
<meta name="twitter:image" content="http://c.biancheng.net/uploads/allimg/181116/3-1Q116095405308.gif">

<link rel="canonical" href="http://hackmgod.gitee.io/2020/01/17/%E3%80%9026%E3%80%91%E6%A8%A1%E6%9D%BF%E6%96%B9%E6%B3%95%E6%A8%A1%E5%BC%8F%EF%BC%88%E6%A8%A1%E6%9D%BF%E6%96%B9%E6%B3%95%E8%AE%BE%E8%AE%A1%E6%A8%A1%E5%BC%8F%EF%BC%89%E8%AF%A6%E8%A7%A3/">


<script id="page-configurations">
  // https://hexo.io/docs/variables.html
  CONFIG.page = {
    sidebar: "",
    isHome: false,
    isPost: true
  };
</script>

  <title>【26】模板方法模式（模板方法设计模式）详解 | H.m博客</title>
  






  <noscript>
  <style>
  .use-motion .brand,
  .use-motion .menu-item,
  .sidebar-inner,
  .use-motion .post-block,
  .use-motion .pagination,
  .use-motion .comments,
  .use-motion .post-header,
  .use-motion .post-body,
  .use-motion .collection-header { opacity: initial; }

  .use-motion .site-title,
  .use-motion .site-subtitle {
    opacity: initial;
    top: initial;
  }

  .use-motion .logo-line-before i { left: initial; }
  .use-motion .logo-line-after i { right: initial; }
  </style>
</noscript>

<link rel="alternate" href="/myblogs/atom.xml" title="H.m博客" type="application/atom+xml">
</head>

<body itemscope itemtype="http://schema.org/WebPage">
  <div class="container use-motion">
    <div class="headband"></div>

    <header class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-container">
  <div class="site-meta">

    <div>
      <a href="/myblogs/" class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">H.m博客</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
        <p class="site-subtitle">www.hackm.cn</p>
  </div>

  <div class="site-nav-toggle">
    <div class="toggle" aria-label="切换导航栏">
      <span class="toggle-line toggle-line-first"></span>
      <span class="toggle-line toggle-line-middle"></span>
      <span class="toggle-line toggle-line-last"></span>
    </div>
  </div>
</div>


<nav class="site-nav">
  
  <ul id="menu" class="menu">
        <li class="menu-item menu-item-home">

    <a href="/myblogs/" rel="section"><i class="fa fa-fw fa-home"></i>首页</a>

  </li>
        <li class="menu-item menu-item-categories">

    <a href="/myblogs/categories/" rel="section"><i class="fa fa-fw fa-th"></i>分类</a>

  </li>
        <li class="menu-item menu-item-archives">

    <a href="/myblogs/archives/" rel="section"><i class="fa fa-fw fa-archive"></i>归档</a>

  </li>
      <li class="menu-item menu-item-search">
        <a role="button" class="popup-trigger"><i class="fa fa-search fa-fw"></i>搜索
        </a>
      </li>
  </ul>

</nav>
  <div class="site-search">
    <div class="popup search-popup">
    <div class="search-header">
  <span class="search-icon">
    <i class="fa fa-search"></i>
  </span>
  <div class="search-input-container">
    <input autocomplete="off" autocorrect="off" autocapitalize="none"
           placeholder="搜索..." spellcheck="false"
           type="text" id="search-input">
  </div>
  <span class="popup-btn-close">
    <i class="fa fa-times-circle"></i>
  </span>
</div>
<div id="search-result"></div>

</div>
<div class="search-pop-overlay"></div>

  </div>
</div>
    </header>

    
  <div class="back-to-top">
    <i class="fa fa-arrow-up"></i>
    <span>0%</span>
  </div>


    <main class="main">
      <div class="main-inner">
        <div class="content-wrap">
          

          <div class="content">
            

  <div class="posts-expand">
      
  
  
  <article itemscope itemtype="http://schema.org/Article" class="post-block " lang="zh-CN">
    <link itemprop="mainEntityOfPage" href="http://hackmgod.gitee.io/2020/01/17/%E3%80%9026%E3%80%91%E6%A8%A1%E6%9D%BF%E6%96%B9%E6%B3%95%E6%A8%A1%E5%BC%8F%EF%BC%88%E6%A8%A1%E6%9D%BF%E6%96%B9%E6%B3%95%E8%AE%BE%E8%AE%A1%E6%A8%A1%E5%BC%8F%EF%BC%89%E8%AF%A6%E8%A7%A3/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="image" content="http://img.hao661.com/zt.hao661.com/uploads/allimg/141006/0644042451-0.jpg">
      <meta itemprop="name" content="H.m">
      <meta itemprop="description" content="欢迎您的到来！">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="H.m博客">
    </span>
      <header class="post-header">
		
        <h1 class="post-title" itemprop="name headline">
          【26】模板方法模式（模板方法设计模式）详解
        </h1>

        <div class="post-meta">
            <span class="post-meta-item">
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              <span class="post-meta-item-text">发表于</span>
              

              <time title="创建时间：2020-01-17 13:59:17 / 修改时间：18:10:03" itemprop="dateCreated datePublished" datetime="2020-01-17T13:59:17+08:00">2020-01-17</time>
            </span>
            <span class="post-meta-item">
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              <span class="post-meta-item-text">分类于</span>
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/myblogs/categories/%E8%AE%BE%E8%AE%A1%E6%A8%A1%E5%BC%8F/" itemprop="url" rel="index">
                    <span itemprop="name">设计模式</span>
                  </a>
                </span>
            </span>

          
            <div class="post-description">模板方法模式（模板方法设计模式）详解</div>

        </div>
      </header>

    
    
    
    <div class="post-body" itemprop="articleBody">

      
        <h2 id="【26】模板方法模式（模板方法设计模式）详解"><a href="#【26】模板方法模式（模板方法设计模式）详解" class="headerlink" title="【26】模板方法模式（模板方法设计模式）详解"></a>【26】模板方法模式（模板方法设计模式）详解</h2><p>在面向对象程序设计过程中，程序员常常会遇到这种情况：设计一个系统时知道了算法所需的关键步骤，而且确定了这些步骤的执行顺序，但某些步骤的具体实现还未知，或者说某些步骤的实现与具体的环境相关。</p>
<p>例如，去银行办理业务一般要经过以下4个流程：取号、排队、办理具体业务、对银行工作人员进行评分等，其中取号、排队和对银行工作人员进行评分的业务对每个客户是一样的，可以在父类中实现，但是办理具体业务却因人而异，它可能是存款、取款或者转账等，可以延迟到子类中实现。</p>
<p>这样的例子在生活中还有很多，例如，一个人每天会起床、吃饭、做事、睡觉等，其中“做事”的内容每天可能不同。我们把这些规定了流程或格式的实例定义成模板，允许使用者根据自己的需求去更新它，例如，简历模板、论文模板、Word 中模板文件等。</p>
<p>以下介绍的模板方法模式将解决以上类似的问题。</p>
<h2 id="模式的定义与特点"><a href="#模式的定义与特点" class="headerlink" title="模式的定义与特点"></a>模式的定义与特点</h2><p>模板方法（Template Method）模式的定义如下：定义一个操作中的算法骨架，而将算法的一些步骤延迟到子类中，使得子类可以不改变该算法结构的情况下重定义该算法的某些特定步骤。它是一种类行为型模式。</p>
<p>该模式的主要优点如下。</p>
<ul>
<li>它封装了不变部分，扩展可变部分。它把认为是不变部分的算法封装到父类中实现，而把可变部分算法由子类继承实现，便于子类继续扩展。</li>
<li>它在父类中提取了公共的部分代码，便于代码复用。</li>
<li>部分方法是由子类实现的，因此子类可以通过扩展方式增加相应的功能，符合开闭原则。</li>
</ul>
<p>该模式的主要缺点如下。</p>
<ul>
<li>对每个不同的实现都需要定义一个子类，这会导致类的个数增加，系统更加庞大，设计也更加抽象。</li>
<li>父类中的抽象方法由子类实现，子类执行的结果会影响父类的结果，这导致一种反向的控制结构，它提高了代码阅读的难度。<h2 id="模式的结构与实现"><a href="#模式的结构与实现" class="headerlink" title="模式的结构与实现"></a>模式的结构与实现</h2>模板方法模式需要注意抽象类与具体子类之间的协作。它用到了虚函数的多态性技术以及“不用调用我，让我来调用你”的反向控制技术。现在来介绍它们的基本结构。<h4 id="1-模式的结构"><a href="#1-模式的结构" class="headerlink" title="1. 模式的结构"></a>1. 模式的结构</h4>模板方法模式包含以下主要角色。</li>
</ul>
<p>(1) 抽象类（Abstract Class）：负责给出一个算法的轮廓和骨架。它由一个模板方法和若干个基本方法构成。这些方法的定义如下。</p>
<p>① 模板方法：定义了算法的骨架，按某种顺序调用其包含的基本方法。</p>
<p>② 基本方法：是整个算法中的一个步骤，包含以下几种类型。<br>抽象方法：在抽象类中申明，由具体子类实现。<br>具体方法：在抽象类中已经实现，在具体子类中可以继承或重写它。<br>钩子方法：在抽象类中已经实现，包括用于判断的逻辑方法和需要子类重写的空方法两种。</p>
<p>(2) 具体子类（Concrete Class）：实现抽象类中所定义的抽象方法和钩子方法，它们是一个顶级逻辑的一个组成步骤。</p>
<p>模板方法模式的结构图如图 1 所示。</p>
<p><img src="http://c.biancheng.net/uploads/allimg/181116/3-1Q116095405308.gif" alt="模板方法模式的结构图"><br>图1 模板方法模式的结构图</p>
<h4 id="2-模式的实现"><a href="#2-模式的实现" class="headerlink" title="2. 模式的实现"></a>2. 模式的实现</h4><p>模板方法模式的代码如下：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br></pre></td><td class="code"><pre><span class="line">package templateMethod;</span><br><span class="line">public class TemplateMethodPattern</span><br><span class="line">&#123;</span><br><span class="line">    public static void main(String[] args)</span><br><span class="line">    &#123;</span><br><span class="line">        AbstractClass tm&#x3D;new ConcreteClass();</span><br><span class="line">        tm.TemplateMethod();</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line">&#x2F;&#x2F;抽象类</span><br><span class="line">abstract class AbstractClass</span><br><span class="line">&#123;</span><br><span class="line">    public void TemplateMethod() &#x2F;&#x2F;模板方法</span><br><span class="line">    &#123;</span><br><span class="line">        SpecificMethod();</span><br><span class="line">        abstractMethod1();          </span><br><span class="line">         abstractMethod2();</span><br><span class="line">    &#125;  </span><br><span class="line">    public void SpecificMethod() &#x2F;&#x2F;具体方法</span><br><span class="line">    &#123;</span><br><span class="line">        System.out.println(&quot;抽象类中的具体方法被调用...&quot;);</span><br><span class="line">    &#125;   </span><br><span class="line">    public abstract void abstractMethod1(); &#x2F;&#x2F;抽象方法1</span><br><span class="line">    public abstract void abstractMethod2(); &#x2F;&#x2F;抽象方法2</span><br><span class="line">&#125;</span><br><span class="line">&#x2F;&#x2F;具体子类</span><br><span class="line">class ConcreteClass extends AbstractClass</span><br><span class="line">&#123;</span><br><span class="line">    public void abstractMethod1()</span><br><span class="line">    &#123;</span><br><span class="line">        System.out.println(&quot;抽象方法1的实现被调用...&quot;);</span><br><span class="line">    &#125;   </span><br><span class="line">    public void abstractMethod2()</span><br><span class="line">    &#123;</span><br><span class="line">        System.out.println(&quot;抽象方法2的实现被调用...&quot;);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>


<p>程序的运行结果如下：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">抽象类中的具体方法被调用...</span><br><span class="line">抽象方法1的实现被调用...</span><br><span class="line">抽象方法2的实现被调用...</span><br></pre></td></tr></table></figure>

<h2 id="模式的应用实例"><a href="#模式的应用实例" class="headerlink" title="模式的应用实例"></a>模式的应用实例</h2><p>【例1】用模板方法模式实现出国留学手续设计程序。</p>
<p>分析：出国留学手续一般经过以下流程：索取学校资料，提出入学申请，办理因私出国护照、出境卡和公证，申请签证，体检、订机票、准备行装，抵达目标学校等，其中有些业务对各个学校是一样的，但有些业务因学校不同而不同，所以比较适合用模板方法模式来实现。</p>
<p>在本实例中，我们先定义一个出国留学的抽象类 StudyAbroad，里面包含了一个模板方法 TemplateMethod()，该方法中包含了办理出国留学手续流程中的各个基本方法，其中有些方法的处理由于各国都一样，所以在抽象类中就可以实现，但有些方法的处理各国是不同的，必须在其具体子类（如美国留学类 StudyInAmerica）中实现。如果再增加一个国家，只要增加一个子类就可以了，图 2 所示是其结构图。</p>
<p><img src="http://c.biancheng.net/uploads/allimg/181116/3-1Q11609544UV.gif" alt="出国留学手续设计程序的结构图"><br>图2 出国留学手续设计程序的结构图</p>
<p>程序代码如下：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br></pre></td><td class="code"><pre><span class="line">package templateMethod;</span><br><span class="line">public class StudyAbroadProcess</span><br><span class="line">&#123;</span><br><span class="line">    public static void main(String[] args)</span><br><span class="line">    &#123;</span><br><span class="line">        StudyAbroad tm&#x3D;new StudyInAmerica();</span><br><span class="line">        tm.TemplateMethod();</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line">&#x2F;&#x2F;抽象类: 出国留学</span><br><span class="line">abstract class StudyAbroad</span><br><span class="line">&#123;</span><br><span class="line">    public void TemplateMethod() &#x2F;&#x2F;模板方法</span><br><span class="line">    &#123;</span><br><span class="line">        LookingForSchool(); &#x2F;&#x2F;索取学校资料</span><br><span class="line">        ApplyForEnrol();    &#x2F;&#x2F;入学申请      </span><br><span class="line">        ApplyForPassport(); &#x2F;&#x2F;办理因私出国护照、出境卡和公证</span><br><span class="line">        ApplyForVisa();     &#x2F;&#x2F;申请签证</span><br><span class="line">        ReadyGoAbroad();    &#x2F;&#x2F;体检、订机票、准备行装</span><br><span class="line">        Arriving();         &#x2F;&#x2F;抵达</span><br><span class="line">    &#125;              </span><br><span class="line">    public void ApplyForPassport()</span><br><span class="line">    &#123;</span><br><span class="line">        System.out.println(&quot;三.办理因私出国护照、出境卡和公证：&quot;);</span><br><span class="line">        System.out.println(&quot;  1）持录取通知书、本人户口簿或身份证向户口所在地公安机关申请办理因私出国护照和出境卡。&quot;);</span><br><span class="line">        System.out.println(&quot;  2）办理出生公证书，学历、学位和成绩公证，经历证书，亲属关系公证，经济担保公证。&quot;);</span><br><span class="line">    &#125;</span><br><span class="line">    public void ApplyForVisa()</span><br><span class="line">    &#123;</span><br><span class="line">        System.out.println(&quot;四.申请签证：&quot;);</span><br><span class="line">        System.out.println(&quot;  1）准备申请国外境签证所需的各种资料，包括个人学历、成绩单、工作经历的证明；个人及家庭收入、资金和财产证明；家庭成员的关系证明等；&quot;);</span><br><span class="line">        System.out.println(&quot;  2）向拟留学国家驻华使(领)馆申请入境签证。申请时需按要求填写有关表格，递交必需的证明材料，缴纳签证。有的国家(比如美国、英国、加拿大等)在申请签证时会要求申请人前往使(领)馆进行面试。&quot;);</span><br><span class="line">    &#125;</span><br><span class="line">    public void ReadyGoAbroad()</span><br><span class="line">    &#123;</span><br><span class="line">        System.out.println(&quot;五.体检、订机票、准备行装：&quot;);</span><br><span class="line">        System.out.println(&quot;  1）进行身体检查、免疫检查和接种传染病疫苗；&quot;);</span><br><span class="line">        System.out.println(&quot;  2）确定机票时间、航班和转机地点。&quot;);</span><br><span class="line">    &#125;</span><br><span class="line">    public abstract void LookingForSchool();&#x2F;&#x2F;索取学校资料</span><br><span class="line">    public abstract void ApplyForEnrol();   &#x2F;&#x2F;入学申请</span><br><span class="line">    public abstract void Arriving();        &#x2F;&#x2F;抵达</span><br><span class="line">&#125;</span><br><span class="line">&#x2F;&#x2F;具体子类: 美国留学</span><br><span class="line">class StudyInAmerica extends StudyAbroad</span><br><span class="line">&#123;</span><br><span class="line">    @Override</span><br><span class="line">    public void LookingForSchool()</span><br><span class="line">    &#123;</span><br><span class="line">        System.out.println(&quot;一.索取学校以下资料：&quot;);</span><br><span class="line">        System.out.println(&quot;  1）对留学意向国家的政治、经济、文化背景和教育体制、学术水平进行较为全面的了解；&quot;);</span><br><span class="line">        System.out.println(&quot;  2）全面了解和掌握国外学校的情况，包括历史、学费、学制、专业、师资配备、教学设施、学术地位、学生人数等；&quot;);</span><br><span class="line">        System.out.println(&quot;  3）了解该学校的住宿、交通、医疗保险情况如何；&quot;);</span><br><span class="line">        System.out.println(&quot;  4）该学校在中国是否有授权代理招生的留学中介公司？&quot;);</span><br><span class="line">        System.out.println(&quot;  5）掌握留学签证情况；&quot;);</span><br><span class="line">        System.out.println(&quot;  6）该国政府是否允许留学生合法打工？&quot;);</span><br><span class="line">        System.out.println(&quot;  8）毕业之后可否移民？&quot;);</span><br><span class="line">        System.out.println(&quot;  9）文凭是否受到我国认可？&quot;);</span><br><span class="line">    &#125;</span><br><span class="line">    @Override</span><br><span class="line">    public void ApplyForEnrol()</span><br><span class="line">    &#123;</span><br><span class="line">        System.out.println(&quot;二.入学申请：&quot;);</span><br><span class="line">        System.out.println(&quot;  1）填写报名表；&quot;);</span><br><span class="line">        System.out.println(&quot;  2）将报名表、个人学历证明、最近的学习成绩单、推荐信、个人简历、托福或雅思语言考试成绩单等资料寄往所申请的学校；&quot;);</span><br><span class="line">        System.out.println(&quot;  3）为了给签证办理留有充裕的时间，建议越早申请越好，一般提前1年就比较从容。&quot;);       </span><br><span class="line">    &#125;</span><br><span class="line">    @Override</span><br><span class="line">    public void Arriving()</span><br><span class="line">    &#123;</span><br><span class="line">        System.out.println(&quot;六.抵达目标学校：&quot;);</span><br><span class="line">        System.out.println(&quot;  1）安排住宿；&quot;);</span><br><span class="line">        System.out.println(&quot;  2）了解校园及周边环境。&quot;);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>


<p>程序的运行结果如下：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br></pre></td><td class="code"><pre><span class="line">一.索取学校以下资料：</span><br><span class="line">  1）对留学意向国家的政治、经济、文化背景和教育体制、学术水平进行较为全面的了解；</span><br><span class="line">  2）全面了解和掌握国外学校的情况，包括历史、学费、学制、专业、师资配备、教学设施、学术地位、学生人数等；</span><br><span class="line">  3）了解该学校的住宿、交通、医疗保险情况如何；</span><br><span class="line">  4）该学校在中国是否有授权代理招生的留学中介公司？</span><br><span class="line">  5）掌握留学签证情况；</span><br><span class="line">  6）该国政府是否允许留学生合法打工？</span><br><span class="line">  8）毕业之后可否移民？</span><br><span class="line">  9）文凭是否受到我国认可？</span><br><span class="line">二.入学申请：</span><br><span class="line">  1）填写报名表；</span><br><span class="line">  2）将报名表、个人学历证明、最近的学习成绩单、推荐信、个人简历、托福或雅思语言考试成绩单等资料寄往所申请的学校；</span><br><span class="line">  3）为了给签证办理留有充裕的时间，建议越早申请越好，一般提前1年就比较从容。</span><br><span class="line">三.办理因私出国护照、出境卡和公证：</span><br><span class="line">  1）持录取通知书、本人户口簿或身份证向户口所在地公安机关申请办理因私出国护照和出境卡。</span><br><span class="line">  2）办理出生公证书，学历、学位和成绩公证，经历证书，亲属关系公证，经济担保公证。</span><br><span class="line">四.申请签证：</span><br><span class="line">  1）准备申请国外境签证所需的各种资料，包括个人学历、成绩单、工作经历的证明；个人及家庭收入、资金和财产证明；家庭成员的关系证明等；</span><br><span class="line">  2）向拟留学国家驻华使(领)馆申请入境签证。申请时需按要求填写有关表格，递交必需的证明材料，缴纳签证。有的国家(比如美国、英国、加拿大等)在申请签证时会要求申请人前往使(领)馆进行面试。</span><br><span class="line">五.体检、订机票、准备行装：</span><br><span class="line">  1）进行身体检查、免疫检查和接种传染病疫苗；</span><br><span class="line">  2）确定机票时间、航班和转机地点。</span><br><span class="line">六.抵达目标学校：</span><br><span class="line">  1）安排住宿；</span><br><span class="line">  2）了解校园及周边环境。</span><br></pre></td></tr></table></figure>

<h2 id="模式的应用场景"><a href="#模式的应用场景" class="headerlink" title="模式的应用场景"></a>模式的应用场景</h2><p>模板方法模式通常适用于以下场景。</p>
<ul>
<li>算法的整体步骤很固定，但其中个别部分易变时，这时候可以使用模板方法模式，将容易变的部分抽象出来，供子类实现。</li>
<li>当多个子类存在公共的行为时，可以将其提取出来并集中到一个公共父类中以避免代码重复。首先，要识别现有代码中的不同之处，并且将不同之处分离为新的操作。最后，用一个调用这些新的操作的模板方法来替换这些不同的代码。</li>
<li>当需要控制子类的扩展时，模板方法只在特定点调用钩子操作，这样就只允许在这些点进行扩展。<h2 id="模式的扩展"><a href="#模式的扩展" class="headerlink" title="模式的扩展"></a>模式的扩展</h2>在模板方法模式中，基本方法包含：抽象方法、具体方法和钩子方法，正确使用“钩子方法”可以使得子类控制父类的行为。如下面例子中，可以通过在具体子类中重写钩子方法 HookMethod1() 和 HookMethod2() 来改变抽象父类中的运行结果，其结构图如图 3 所示。</li>
</ul>
<p><img src="http://c.biancheng.net/uploads/allimg/181116/3-1Q116095550123.gif" alt="含钩子方法的模板方法模式的结构图"><br>图3 含钩子方法的模板方法模式的结构图</p>
<p>程序代码如下：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br></pre></td><td class="code"><pre><span class="line">package templateMethod;</span><br><span class="line">public class HookTemplateMethod</span><br><span class="line">&#123;</span><br><span class="line">    public static void main(String[] args)</span><br><span class="line">    &#123;</span><br><span class="line">        HookAbstractClass tm&#x3D;new HookConcreteClass();</span><br><span class="line">        tm.TemplateMethod();</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line">&#x2F;&#x2F;含钩子方法的抽象类</span><br><span class="line">abstract class HookAbstractClass</span><br><span class="line">&#123;</span><br><span class="line">    public void TemplateMethod() &#x2F;&#x2F;模板方法</span><br><span class="line">    &#123;</span><br><span class="line">        abstractMethod1();</span><br><span class="line">        HookMethod1();</span><br><span class="line">        if(HookMethod2())</span><br><span class="line">        &#123;</span><br><span class="line">            SpecificMethod();   </span><br><span class="line">        &#125;</span><br><span class="line">         abstractMethod2();</span><br><span class="line">    &#125;  </span><br><span class="line">    public void SpecificMethod() &#x2F;&#x2F;具体方法</span><br><span class="line">    &#123;</span><br><span class="line">        System.out.println(&quot;抽象类中的具体方法被调用...&quot;);</span><br><span class="line">    &#125;</span><br><span class="line">    public void HookMethod1()&#123;&#125;  &#x2F;&#x2F;钩子方法1</span><br><span class="line">    public boolean HookMethod2() &#x2F;&#x2F;钩子方法2</span><br><span class="line">    &#123;</span><br><span class="line">        return true;</span><br><span class="line">    &#125;</span><br><span class="line">    public abstract void abstractMethod1(); &#x2F;&#x2F;抽象方法1</span><br><span class="line">    public abstract void abstractMethod2(); &#x2F;&#x2F;抽象方法2</span><br><span class="line">&#125;</span><br><span class="line">&#x2F;&#x2F;含钩子方法的具体子类</span><br><span class="line">class HookConcreteClass extends HookAbstractClass</span><br><span class="line">&#123;</span><br><span class="line">    public void abstractMethod1()</span><br><span class="line">    &#123;</span><br><span class="line">        System.out.println(&quot;抽象方法1的实现被调用...&quot;);</span><br><span class="line">    &#125;   </span><br><span class="line">    public void abstractMethod2()</span><br><span class="line">    &#123;</span><br><span class="line">        System.out.println(&quot;抽象方法2的实现被调用...&quot;);</span><br><span class="line">    &#125;   </span><br><span class="line">    public void HookMethod1()</span><br><span class="line">    &#123;</span><br><span class="line">        System.out.println(&quot;钩子方法1被重写...&quot;);</span><br><span class="line">    &#125;</span><br><span class="line">    public boolean HookMethod2()</span><br><span class="line">    &#123;</span><br><span class="line">        return false;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>


<p>程序的运行结果如下：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">抽象方法1的实现被调用...</span><br><span class="line">钩子方法1被重写...</span><br><span class="line">抽象方法2的实现被调用...</span><br></pre></td></tr></table></figure>


<p>如果钩子方法 HookMethod1() 和钩子方法 HookMethod2() 的代码改变，则程序的运行结果也会改变。</p>

    </div>

    
    
    

      <footer class="post-footer">

        


        
    <div class="post-nav">
      <div class="post-nav-item">
    <a href="/myblogs/2020/01/17/%E3%80%9028%E3%80%91%E5%91%BD%E4%BB%A4%E6%A8%A1%E5%BC%8F%EF%BC%88%E8%AF%A6%E8%A7%A3%E7%89%88%EF%BC%89/" rel="prev" title="【28】命令模式（详解版）">
      <i class="fa fa-chevron-left"></i> 【28】命令模式（详解版）
    </a></div>
      <div class="post-nav-item">
    <a href="/myblogs/2020/01/17/%E3%80%9027%E3%80%91%E7%AD%96%E7%95%A5%E6%A8%A1%E5%BC%8F%EF%BC%88%E7%AD%96%E7%95%A5%E8%AE%BE%E8%AE%A1%E6%A8%A1%E5%BC%8F%EF%BC%89%E8%AF%A6%E8%A7%A3/" rel="next" title="【27】策略模式（策略设计模式）详解">
      【27】策略模式（策略设计模式）详解 <i class="fa fa-chevron-right"></i>
    </a></div>
    </div>
      </footer>
    
  </article>
  
  
  

  </div>


          </div>
          

<script>
  window.addEventListener('tabs:register', () => {
    let activeClass = CONFIG.comments.activeClass;
    if (CONFIG.comments.storage) {
      activeClass = localStorage.getItem('comments_active') || activeClass;
    }
    if (activeClass) {
      let activeTab = document.querySelector(`a[href="#comment-${activeClass}"]`);
      if (activeTab) {
        activeTab.click();
      }
    }
  });
  if (CONFIG.comments.storage) {
    window.addEventListener('tabs:click', event => {
      if (!event.target.matches('.tabs-comment .tab-content .tab-pane')) return;
      let commentClass = event.target.classList[1];
      localStorage.setItem('comments_active', commentClass);
    });
  }
</script>

        </div>
          
  
  <div class="toggle sidebar-toggle">
    <span class="toggle-line toggle-line-first"></span>
    <span class="toggle-line toggle-line-middle"></span>
    <span class="toggle-line toggle-line-last"></span>
  </div>

  <aside class="sidebar">
    <div class="sidebar-inner">

      <ul class="sidebar-nav motion-element">
        <li class="sidebar-nav-toc">
          文章目录
        </li>
        <li class="sidebar-nav-overview">
          站点概览
        </li>
      </ul>

      <!--noindex-->
      <div class="post-toc-wrap sidebar-panel">
          <div class="post-toc motion-element"><ol class="nav"><li class="nav-item nav-level-2"><a class="nav-link" href="#【26】模板方法模式（模板方法设计模式）详解"><span class="nav-number">1.</span> <span class="nav-text">【26】模板方法模式（模板方法设计模式）详解</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#模式的定义与特点"><span class="nav-number">2.</span> <span class="nav-text">模式的定义与特点</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#模式的结构与实现"><span class="nav-number">3.</span> <span class="nav-text">模式的结构与实现</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#1-模式的结构"><span class="nav-number">3.0.1.</span> <span class="nav-text">1. 模式的结构</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#2-模式的实现"><span class="nav-number">3.0.2.</span> <span class="nav-text">2. 模式的实现</span></a></li></ol></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#模式的应用实例"><span class="nav-number">4.</span> <span class="nav-text">模式的应用实例</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#模式的应用场景"><span class="nav-number">5.</span> <span class="nav-text">模式的应用场景</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#模式的扩展"><span class="nav-number">6.</span> <span class="nav-text">模式的扩展</span></a></li></ol></div>
      </div>
      <!--/noindex-->

      <div class="site-overview-wrap sidebar-panel">
        <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
    <img class="site-author-image" itemprop="image" alt="H.m"
      src="http://img.hao661.com/zt.hao661.com/uploads/allimg/141006/0644042451-0.jpg">
  <p class="site-author-name" itemprop="name">H.m</p>
  <div class="site-description" itemprop="description">欢迎您的到来！</div>
</div>
<div class="site-state-wrap motion-element">
  <nav class="site-state">
      <div class="site-state-item site-state-posts">
          <a href="/myblogs/archives/">
        
          <span class="site-state-item-count">42</span>
          <span class="site-state-item-name">日志</span>
        </a>
      </div>
      <div class="site-state-item site-state-categories">
            <a href="/myblogs/categories/">
          
        <span class="site-state-item-count">3</span>
        <span class="site-state-item-name">分类</span></a>
      </div>
  </nav>
</div>
  <div class="links-of-author motion-element">
      <span class="links-of-author-item">
        <a href="https://github.com/hackmgod" title="GitHub → https:&#x2F;&#x2F;github.com&#x2F;hackmgod" rel="noopener" target="_blank"><i class="fa fa-fw fa-github"></i>GitHub</a>
      </span>
      <span class="links-of-author-item">
        <a href="/myblogs/hackmgod@foxmail.com" title="E-Mail → hackmgod@foxmail.com"><i class="fa fa-fw fa-envelope"></i>E-Mail</a>
      </span>
      <span class="links-of-author-item">
        <a href="/myblogs/975643993@qq.com" title="QQ → 975643993@qq.com"><i class="fa fa-fw fa-qq"></i>QQ</a>
      </span>
      <span class="links-of-author-item">
        <a href="/myblogs/atom.xml" title="RSS → &#x2F;atom.xml"><i class="fa fa-fw fa-rss"></i>RSS</a>
      </span>
  </div>


  <div class="links-of-blogroll motion-element">
    <div class="links-of-blogroll-title">
      <i class="fa fa-fw fa-link"></i>
      友情链接
    </div>
    <ul class="links-of-blogroll-list">
        <li class="links-of-blogroll-item">
          <a href="https://www.baidu.com/" title="https:&#x2F;&#x2F;www.baidu.com&#x2F;" rel="noopener" target="_blank">百度</a>
        </li>
        <li class="links-of-blogroll-item">
          <a href="https://www.iqiyi.com/" title="https:&#x2F;&#x2F;www.iqiyi.com&#x2F;" rel="noopener" target="_blank">爱奇艺</a>
        </li>
    </ul>
  </div>

      </div>

    </div>
  </aside>
  <div id="sidebar-dimmer"></div>


      </div>
    </main>

    <footer class="footer">
      <div class="footer-inner">
        <!-- 用下面的符号注释，注释代码用下面括号括起来 -->
<!-- -->

<div class="copyright">
  
  &copy; 
  <span itemprop="copyrightYear">2020</span>
  <span class="with-love">
    <i class="fa fa-user"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">H.m</span>
</div>


<!--
  <div class="powered-by">由 <a href="https://hexo.io/" class="theme-link" rel="noopener" target="_blank">Hexo</a> 强力驱动 v4.2.0
  </div>
  <span class="post-meta-divider">|</span>
  <div class="theme-info">主题 – <a href="https://theme-next.org/" class="theme-link" rel="noopener" target="_blank">NexT.Gemini</a> v7.7.0
  </div> -->

<script async src="//busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script>

<div class="powered-by">
  <i class="fa fa-user-md"></i>
  <span id="busuanzi_container_site_pv">
    本站访问量:<span id="busuanzi_value_site_pv"></span>次
  </span>
  <span class="post-meta-divider">|</span>
  <span id="busuanzi_container_site_uv">
    本站总访客量：<span id="busuanzi_value_site_uv"></span>人
  </span>
</div>





        








      </div>
    </footer>
  </div>

  
  <script src="/myblogs/lib/anime.min.js"></script>
  <script src="/myblogs/lib/velocity/velocity.min.js"></script>
  <script src="/myblogs/lib/velocity/velocity.ui.min.js"></script>

<script src="/myblogs/js/utils.js"></script>

<script src="/myblogs/js/motion.js"></script>


<script src="/myblogs/js/schemes/pisces.js"></script>


<script src="/myblogs/js/next-boot.js"></script>




  




  
<script src="/myblogs/js/local-search.js"></script>













  

  

</body>
</html>


<a href="https://github.com/hackmgod" target="_blank" rel="noopener" class="github-corner" aria-label="View source on GitHub"><svg width="80" height="80" viewBox="0 0 250 250" style="fill:#151513; color:#fff; position: absolute; top: 0; border: 0; right: 0;" aria-hidden="true"><path d="M0,0 L115,115 L130,115 L142,142 L250,250 L250,0 Z"></path><path d="M128.3,109.0 C113.8,99.7 119.0,89.6 119.0,89.6 C122.0,82.7 120.5,78.6 120.5,78.6 C119.2,72.0 123.4,76.3 123.4,76.3 C127.3,80.9 125.5,87.3 125.5,87.3 C122.9,97.6 130.6,101.9 134.4,103.2" fill="currentColor" style="transform-origin: 130px 106px;" class="octo-arm"></path><path d="M115.0,115.0 C114.9,115.1 118.7,116.5 119.8,115.4 L133.7,101.6 C136.9,99.2 139.9,98.4 142.2,98.6 C133.8,88.0 127.5,74.4 143.8,58.0 C148.5,53.4 154.0,51.2 159.7,51.0 C160.3,49.4 163.2,43.6 171.4,40.1 C171.4,40.1 176.1,42.5 178.8,56.2 C183.1,58.6 187.2,61.8 190.9,65.4 C194.5,69.0 197.7,73.2 200.1,77.6 C213.8,80.2 216.3,84.9 216.3,84.9 C212.7,93.1 206.9,96.0 205.4,96.6 C205.1,102.4 203.0,107.8 198.3,112.5 C181.9,128.9 168.3,122.5 157.7,114.1 C157.9,116.9 156.7,120.9 152.7,124.9 L141.0,136.5 C139.8,137.7 141.6,141.9 141.8,141.8 Z" fill="currentColor" class="octo-body"></path></svg></a><style>.github-corner:hover .octo-arm{animation:octocat-wave 560ms ease-in-out}@keyframes octocat-wave{0%,100%{transform:rotate(0)}20%,60%{transform:rotate(-25deg)}40%,80%{transform:rotate(10deg)}}@media (max-width:500px){.github-corner:hover .octo-arm{animation:none}.github-corner .octo-arm{animation:octocat-wave 560ms ease-in-out}}</style>


<!-- 动态背景 -->
<script type="text/javascript" src="//cdn.bootcss.com/canvas-nest.js/1.0.0/canvas-nest.min.js"></script>
<!-- 页面点击小红心 -->
<script type="text/javascript" src="/js/src/clicklove.js"></script>